package org.budo.sms.service.dxw;

import java.util.Map;

import org.budo.support.http.client.Request;
import org.budo.support.http.client.Response;
import org.budo.support.java.net.util.UrlEncodeUtil;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

/**
 * @author lmw
 * 
 * @see http://cms.dxw.info/static/index.html#/home/developer/interface/info/1
 */
@Slf4j
@Getter
@Setter
public class BudoDxwSmsServiceImpl implements BudoDxwSmsService {
    private static final String URL_SINGLE_SEND = "http://api.1cloudsp.com/api/v2/single_send"; // 单发验证码短信接口

    private static final String URL_SEND = "http://api.1cloudsp.com/api/v2/send"; // 群发接口，固定内容，后审核

    private String accessKey;

    private String secretKey;

    @Override
    public String sendSms(String to, String template, Map<String, Object> parameters) {
        return this.send(to, template, parameters);
    }

    protected String send(String to, String template, Map<String, Object> parameters) {
        Request request = prepareRequest(to, parameters);
        request.setUrl(URL_SEND);

        // 直接传短信内容，需要人工审核
        String _templateEncode = UrlEncodeUtil.encode(template);
        request.setParameter("content", _templateEncode);

        return this.executeRequest(request);
    }

    protected String single_send(String to, String template, Map<String, Object> parameters) {
        Request request = this.prepareRequest(to, parameters);

        request.setParameter("templateId", template);
        request.setUrl(URL_SINGLE_SEND);

        String _content = (String) parameters.get("content");
        String _contentEncode = UrlEncodeUtil.encode(_content);
        request.setParameter("content", _contentEncode);

        return this.executeRequest(request); // {"code":"0","msg":"SUCCESS","smUuid":"202981_1_0_13699466308_2_Z21SxBL_1"}
    }

    private String executeRequest(Request request) {
        Response response = request.execute();
        log.info("#53 response=" + response);

        String _response = response + "";
        return _response;
    }

    private Request prepareRequest(String to, Map<String, Object> parameters) {
        Request request = new Request();

        request.setParameter("accesskey", this.getAccessKey());
        request.setParameter("secret", this.getSecretKey());

        String _sign = (String) parameters.get("sign");
        String _signEncode = UrlEncodeUtil.encode(_sign);
        request.setParameter("sign", _signEncode);

        request.setParameter("mobile", to);
        return request;
    }
}